package com.jlwl.houseservice.controller;

import com.jlwl.houseservice.common.Result;
import com.jlwl.houseservice.entity.User;
import com.jlwl.houseservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<User> getCurrentUserInfo() {
        // 从安全上下文中获取当前用户名
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        // 根据用户名获取用户信息
        User user = userService.lambdaQuery().eq(User::getPhone, username).one();
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 清除敏感信息
        user.setPassword(null);
        
        return Result.success(user);
    }

    /**
     * 获取指定用户信息
     */
    @GetMapping("/{id}")
    public Result<User> getUserInfo(@PathVariable Integer id) {
        User user = userService.getUserInfo(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
    public Result<Void> updateUserInfo(@RequestBody User user) {
        // 从安全上下文中获取当前用户名
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        // 根据用户名获取用户信息
        User currentUser = userService.lambdaQuery().eq(User::getPhone, username).one();
        if (currentUser == null) {
            return Result.error("用户不存在");
        }
        
        // 设置ID，确保只能修改当前用户信息
        user.setId(currentUser.getId());
        
        boolean success = userService.updateUserInfo(user);
        if (success) {
            return Result.success();
        } else {
            return Result.error("更新失败");
        }
    }
} 